package com.ikangtai.shecare.main;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.PaintDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bugtags.library.Bugtags;
import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.App;
import com.ikangtai.shecare.common.Constant;
import com.ikangtai.shecare.common.CoreService;
import com.ikangtai.shecare.common.al.Algorithm;
import com.ikangtai.shecare.common.al.CycleUnitDS;
import com.ikangtai.shecare.common.al.DayUnitDSInput;
import com.ikangtai.shecare.common.al.DayUnitDSOutput;
import com.ikangtai.shecare.common.al.UserUnitDS;
import com.ikangtai.shecare.common.baseView.NoScrollViewPager;
import com.ikangtai.shecare.common.db.DBManager;
import com.ikangtai.shecare.common.db.sync.SyncALData;
import com.ikangtai.shecare.common.db.sync.SyncRecordInfo;
import com.ikangtai.shecare.common.eventBusMsg.AlgoUpdateMsg;
import com.ikangtai.shecare.common.eventBusMsg.ChooseDate;
import com.ikangtai.shecare.common.eventBusMsg.CurveMsg;
import com.ikangtai.shecare.common.eventBusMsg.MyDeviceMsg;
import com.ikangtai.shecare.common.eventBusMsg.RecordChange;
import com.ikangtai.shecare.common.eventBusMsg.RecordInfo;
import com.ikangtai.shecare.common.eventBusMsg.TemperUploadMsg;
import com.ikangtai.shecare.common.eventBusMsg.ViewPagerNumMsg;
import com.ikangtai.shecare.common.eventBusMsg.WebviewInitDataMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncALDataMsg;
import com.ikangtai.shecare.common.eventBusMsg.sync.SyncRecordInfoMsg;
import com.ikangtai.shecare.common.services.ble.BLEBroadcastReceiver;
import com.ikangtai.shecare.common.services.ble.BLEThermometerService;
import com.ikangtai.shecare.common.util.AppLog;
import com.ikangtai.shecare.common.util.DateUtil;
import com.ikangtai.shecare.common.util.DisplayUtil;
import com.ikangtai.shecare.common.util.ExampleUtil;
import com.ikangtai.shecare.common.util.InternetUtil;
import com.ikangtai.shecare.common.util.OKHttpUtil;
import com.ikangtai.shecare.common.util.PushUtil;
import com.ikangtai.shecare.personal.MyDeviceChooseActivity;
import com.ikangtai.shecare.record.bean.UserRecordData;
import com.ikangtai.shecare.record.bean.UserTemperatureInfo;
import com.ikangtai.shecare.stickycalendar.fragment.CalendarRecordFragment;
import com.jaeger.library.StatusBarUtil;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subcriber;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CopyOnWriteArrayList;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends FragmentActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {


    public static boolean isForeground = false;

    private Context mContext = null;
    //private WebView webview;
    private PopupWindow popupWindow;
    private ViewGroup pop_window1;
    private ViewGroup pop_window2;
    private LinearLayout pop_control_bar_front_holder, pop_control_bar_holder;
    private int statusBarHeight;
    private int mWidth;
    private int mHeight;
    private Handler mHandler = new Handler();
    RecordFragment recordFragment = new RecordFragment();
    CalendarRecordFragment calendarRecordFragment = new CalendarRecordFragment();

    private LinearLayout main_lin;
    private ChangeColorIconWithTextView one, two, three, four, five;

    private NoScrollViewPager mViewPager;
    private List<Fragment> mTabs = new ArrayList<Fragment>();
    private MyFragmentPagerAdapter mAdapter;

    public static final int PAGE_ONE = 0;
    public static final int PAGE_TWO = 1;
    public static final int PAGE_THREE = 2;
    public static final int PAGE_FOUR = 3;
    public static final int PAGE_FIVE = 4;
    private List<ChangeColorIconWithTextView> mTabIndicator = new ArrayList<ChangeColorIconWithTextView>();


//    private Class fragmentArray[] = {HomeFragment.class, RecordFragment.class, HealthFragment.class,
//            KnowledgeFragment.class, PersonalFragment.class};

    private Class fragmentArray[] = {HomeFragment.class, CalendarRecordFragment.class, HealthFragment.class,
            KnowledgeFragment.class, PersonalFragment.class};

    private boolean sign = false;
    public static BLEThermometerService mBLEThermometerService = null;
    private static boolean mScanning;
    public final long SCAN_PERIOD = 5000L;
    private BluetoothDevice mDevice = null;


    private int readnum_flag1 = 0;
    public final String DATABASE = "Database";
    public int THERMOMETER_CONNECTED_NUM = 0;
    public int THERMOMETER_CONNECTED_END_NUM = 0;
    private RecordFragment mRecordFragment;
    private HomeFragment mHomeFragment;
    private String homeConnectStateText;
    private boolean isBLERegistered = false;
    private String deviceName;
    private DBManager dbManager;
    private boolean isBindedToHomeFragment = false;
    private boolean isChosedDateToRecord = false;
    private Algorithm algorithm;
    public static String chosedDateCalendar = "";
    public List<UserTemperatureInfo> temperatureInfoList = new CopyOnWriteArrayList<UserTemperatureInfo>();
    public List<UserTemperatureInfo> syncTemperatureInfoList = new CopyOnWriteArrayList<UserTemperatureInfo>();
    public List<UserRecordData> syncRecordDataList = new CopyOnWriteArrayList<UserRecordData>();
    private boolean isActivityShown = false;
    private ProgressDialog progressDialog;
    public int numFlag1 = 0;
    private boolean isNeedChangeForecast = false;
    private final BLEBroadcastReceiver mGattUpdateReceiver = new BLEBroadcastReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        long t1 = System.currentTimeMillis();
        AppLog.i("LifeCycle get in MainActivity onCreate!");

        super.onCreate(savedInstanceState);

        if (savedInstanceState == null)
            AppLog.i("MainActivity savedInstanceState is null!");
        else {
            AppLog.i("MainActivity savedInstanceState is NOT null!");
            protectApp();
        }

        // appKilledFlag 为 -1 说明程序被杀掉
        if (App.appKilledFlag == -1) {
            AppLog.i("shecare is killed by Android OS! now begin onCreate!");
            protectApp();
        } else
            AppLog.i("shecare normally onCreate!");

        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        dbManager = new DBManager(this);
        algorithm = new Algorithm(this);
        initView();
        initData();
        initJP();

        Intent intent = new Intent(this, CoreService.class);
        startService(intent);
        registerMessageReceiver();
//        bindPushId();
        App.clearAllActivities();
        App.activityList.add(this);

        long currentDayCycleUnitDSMensesStartConfirm = dbManager.getSelectedDayCycleUnitDSMensesStartConfirm(App.userName, new Date().getTime() / 1000);

        if(null != App.DayUnitDSOutputMap.get(currentDayCycleUnitDSMensesStartConfirm)){
            AppLog.e("DayUnitDSOutputMap:" + App.DayUnitDSOutputMap.get(currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm);
            if(App.DayUnitDSOutputMap.get(currentDayCycleUnitDSMensesStartConfirm).periodAchieveConfirm == 0){
                isNeedChangeForecast = true;
            }
        }else
            AppLog.e("App.DayUnitDSOutputMap.get(currentDayCycleUnitDSMensesStartConfirm) is NULL, " +
                    "currentDayCycleUnitDSMensesStartConfirm:" + currentDayCycleUnitDSMensesStartConfirm);

        long t2 = System.currentTimeMillis();
        AppLog.i("LifeCycle get in MainActivity onCreate end! time = " + (t2 - t1));
    }

    @Override
    protected void onStart() {
        super.onStart();
        AppLog.i("LifeCycle MainActivity onStart!");
    }

    @Override
    public void onAttachFragment(android.app.Fragment fragment) {
        super.onAttachFragment(fragment);
        AppLog.i("LifeCycle MainActivity onAttachFragment!");
    }

    private void initJP() {
        JPushInterface.init(getApplicationContext());
        PushUtil.postPushId(getApplicationContext());
        setAlias();
    }

    private void syncRecordAndALData() {

        if (InternetUtil.hasInternet()) {
            SyncRecordInfoMsg syncRecordInfoMsg = new SyncRecordInfoMsg();
            syncRecordInfoMsg.setSyncInActivity(SyncRecordInfoMsg.SYNC_RECORD_NORMAL);
            SyncRecordInfo syncRecordInfo = new SyncRecordInfo(MainActivity.this, syncRecordInfoMsg);
            AppLog.e("SyncRecordInfoWithNetwork");
            syncRecordInfo.syncRecordInfoWithNetwork();

        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("bgFlag", true);
        AppLog.i("LifeCycle MainActivity onSaveInstanceState!");
    }

    protected void protectApp() {
        Intent intent = new Intent(this, SplashActivity.class);
        intent.putExtra("appKilled", true);
        startActivity(intent);

        finish();
    }

    @Override
    protected void onResumeFragments() {
        super.onResumeFragments();
        AppLog.i("LifeCycle MainActivity onResumeFragments!");
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        AppLog.i("LifeCycle MainActivity onPostResume!");
    }

//    @Subcriber
//    private void handleHomeFragmentVisibleMsg(HomeFragmentVisibleMsg homeFragmentVisibleMsg){
//        initBluetooth();
//    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // 当新设置中，屏幕布局模式为横排时
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //TODO 横屏，调整webview为全屏
            AppLog.i("MainActivity is now ORIENTATION_LANDSCAPE");

        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //TODO 竖屏，调整webview和下半部分的比例
            AppLog.i("MainActivity is now ORIENTATION_PORTRAIT");
        }

    }

    public void showProgressDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage(getString(R.string.bbt_post_start));
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    //算法返回值为234时调用一代转二代
    private void g1Tog2Algorithm(){
        UserUnitDS userData = new UserUnitDS();
        userData.averageMenstruationLength = App.memory_preference_mensesLen;
        userData.averageCycleLength = App.memory_preference_periodLen;
        DayUnitDSInput[] dayInput = dbManager.getDayInputListFromG1Record(App.userName);
        algorithm.g1FirstLoginG2(userData, dayInput, 0);
        checkIfNeedDealHistoryData();
    }

    private void checkIfNeedDealHistoryData() {
        CycleUnitDS[] cycleUnitDSes = dbManager.getALCycleOutput(App.userName, null);
        if(null != cycleUnitDSes && cycleUnitDSes.length > 0){
            for(int i = 0; i < cycleUnitDSes.length; i++){
                cycleUnitDSes[i].ovulationDayUserRecordBasis = -99;
            }
            dbManager.saveALCycleOutput(cycleUnitDSes, 0);
        }

        List<DayUnitDSOutput> dayUnitDSOutputs = dbManager.getALDayUnitDSOutputList(App.userName);
        if(null != dayUnitDSOutputs && dayUnitDSOutputs.size() > 0){
            for(int i = 0; i < dayUnitDSOutputs.size(); i++){
                dayUnitDSOutputs.get(i).periodAchieveForecast = 99;
            }
            dbManager.saveALDayOutput(dayUnitDSOutputs, 0);
        }
        saveALResult2Sqlite(0);
    }

    private void saveALResult2Sqlite(int isSynced) {
        algorithm.saveALData2Sqlite(isSynced);
    }


    private void initView() {
        mContext = this;
        //initWebview();

        setOverflowShowingAlways();

        mViewPager = (NoScrollViewPager) findViewById(R.id.fragmentContent);
        mViewPager.setNoScroll(true);

        mTabs = new ArrayList<Fragment>();
        HomeFragment myFragment1 = new HomeFragment();
//        RecordFragment myFragment2 = new RecordFragment();
        CalendarRecordFragment myFragment2 = new CalendarRecordFragment();
        HealthFragment myFragment3 = new HealthFragment();
        KnowledgeFragment myFragment4 = new KnowledgeFragment();
        PersonalFragment myFragment5 = new PersonalFragment();
        mTabs.add(myFragment1);
        mTabs.add(myFragment2);
        mTabs.add(myFragment3);
        mTabs.add(myFragment4);
        mTabs.add(myFragment5);
        mAdapter = new MyFragmentPagerAdapter(this, getSupportFragmentManager(), mTabs);
        mViewPager.setAdapter(mAdapter);

        //表示homeFragment左右预加载几个
        mViewPager.setOffscreenPageLimit(4);

        mViewPager.setOnPageChangeListener(this);
        initTabIndicator();

    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (positionOffset > 0) {
            ChangeColorIconWithTextView left = mTabIndicator.get(position);
            ChangeColorIconWithTextView right = mTabIndicator.get(position + 1);
            left.setIconAlpha(1 - positionOffset);
//            right.setIcon(R.drawable.bottom_health_selected_0);
            right.setIconAlpha(positionOffset);
        }
    }


    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
//                StatusBarUtil.setColor(this, getResources().getColor(App.getPreferenceInt(Constant.kStatusColor)), 0);
                one.setIcon(R.drawable.bottom_home_selected1);
                two.setIcon(R.drawable.bottom_health1);
                three.setIcon(R.drawable.bottom_record1);
                four.setIcon(R.drawable.bottom_knowledge1);
                five.setIcon(R.drawable.bottom_user1);
                one.setIconAlpha(0);
                break;
            case 1:
//                StatusBarUtil.setColor(this, getResources().getColor(R.color.orange), 0);
                two.setIcon(R.drawable.bottom_health_selected1);
                two.setIconAlpha(0);
                one.setIcon(R.drawable.bottom_home1);
                three.setIcon(R.drawable.bottom_record1);
                four.setIcon(R.drawable.bottom_knowledge1);
                five.setIcon(R.drawable.bottom_user1);
                one.setIconAlpha(0);
                break;
            case 2:

//
                three.setIcon(R.drawable.bottom_record_selected1);
                three.setIconAlpha(0);
                two.setIcon(R.drawable.bottom_health1);
                one.setIcon(R.drawable.bottom_home1);
                four.setIcon(R.drawable.bottom_knowledge1);
                five.setIcon(R.drawable.bottom_user1);
                one.setIconAlpha(0);
                break;
            case 3:
//                StatusBarUtil.setColor(this, getResources().getColor(R.color.orange), 0);
                four.setIcon(R.drawable.bottom_knowledge_selected1);
                four.setIconAlpha(0);
                two.setIcon(R.drawable.bottom_health1);
                three.setIcon(R.drawable.bottom_record1);
                one.setIcon(R.drawable.bottom_home1);
                five.setIcon(R.drawable.bottom_user1);
                one.setIconAlpha(0);
                break;
            case 4:
                five.setIcon(R.drawable.bottom_user_selected1);
                five.setIconAlpha(0);
                two.setIcon(R.drawable.bottom_health1);
                three.setIcon(R.drawable.bottom_record1);
                four.setIcon(R.drawable.bottom_knowledge1);
                one.setIcon(R.drawable.bottom_home1);
                one.setIconAlpha(0);
                StatusBarUtil.setColor(this, getResources().getColor(R.color.orange), 0);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void initTabIndicator() {
        main_lin = (LinearLayout) findViewById(R.id.main_lin);
        one = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_one);
        two = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_two);
        three = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_three);
        four = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_four);
        five = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_five);

        mTabIndicator.add(one);
        mTabIndicator.add(two);
        mTabIndicator.add(three);
        mTabIndicator.add(four);
        mTabIndicator.add(five);

        one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetOtherTabs();
                mTabIndicator.get(0).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(0, false);

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                DisplayUtil.setFullScreen(MainActivity.this, false);
            }
        });
        two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                resetOtherTabs();
                mTabIndicator.get(1).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(1, false);

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                DisplayUtil.setFullScreen(MainActivity.this, false);
            }
        });
        three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetOtherTabs();
                main_lin.setVisibility(View.GONE);
                three.setVisibility(View.GONE);

                mTabIndicator.get(2).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(2, false);

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                DisplayUtil.setFullScreen(MainActivity.this, true);
            }
        });
        four.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetOtherTabs();
                mTabIndicator.get(3).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(3, false);

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                DisplayUtil.setFullScreen(MainActivity.this, false);
            }
        });
        five.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetOtherTabs();
                mTabIndicator.get(4).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(4, false);

                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                DisplayUtil.setFullScreen(MainActivity.this, false);
            }
        });
        one.setIconAlpha(1.0f);
    }

    /**
     * 重置其他的Tab
     */
    private void resetOtherTabs() {
        for (int i = 0; i < mTabIndicator.size(); i++) {
            mTabIndicator.get(i).setIconAlpha(0);
        }
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    private void setOverflowShowingAlways() {
        try {
            // true if a permanent menu key is present, false otherwise.
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    private void initWebview() {
//        webview = (WebView) findViewById(R.id.webview);
//        WebViewCfg webViewCfg = new WebViewCfg(webview);
//        webview = webViewCfg.getCfgedWebView(this, false);
//    }

    private void initData() {
        App.status = App.memory_preference_userState;
    }

    private void initBluetooth() {
        // 绑定服务
        Intent gattServiceIntent = new Intent(MainActivity.this, BLEThermometerService.class);
        sign = getApplicationContext().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }


    private View getView(int i) {
        //取得布局实例
        View view = View.inflate(MainActivity.this, R.layout.tab_content, null);

        //取得布局对象
        ImageView imageView = (ImageView) view.findViewById(R.id.image);
        TextView textView = (TextView) view.findViewById(R.id.text);

        Resources r = getResources();
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageView.getLayoutParams();
        params.topMargin = (int) r.getDimension(R.dimen.fragmentTabHost_img_record_marginTop);
        params.bottomMargin = (int) r.getDimension(R.dimen.fragmentTabHost_img_record_marginBottom);
        imageView.setLayoutParams(params);


        if (2 == i) {
            Resources rs = getResources();
            LinearLayout.LayoutParams sparams = (LinearLayout.LayoutParams) imageView.getLayoutParams();
            params.height = (int) rs.getDimension(R.dimen.fragmentTabHost_img_record_height);
            params.topMargin = (int) rs.getDimension(R.dimen.fragmentTabHost_cenimg_record_marginTop);
            imageView.setLayoutParams(sparams);
        }


        return view;
    }

    private class RecordClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
//            LinearLayout fragmentTabHostWrapper = (LinearLayout)optimizedFragmentTabHost.getParent();
//            fragmentTabHostWrapper.setVisibility(View.INVISIBLE);
//            optimizedFragmentTabHost.setCurrentTab(2);

//
        }
    }

    /**
     * 弹出pop框
     *
     * @param view
     */
    private void showPopupWindow(View view) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.record_popup_window, null);
        popupWindow.setContentView(contentView);
        pop_window1 = (ViewGroup) contentView.findViewById(R.id.record_pop_window1);
        showAnimation(pop_window1);
        pop_window2 = (ViewGroup) contentView.findViewById(R.id.record_pop_window2);

        ImageView close = (ImageView) contentView.findViewById(R.id.record_pop_control_bar_front_close_img);
        pop_control_bar_front_holder = (LinearLayout) contentView.findViewById(R.id.record_pop_control_bar_front_holder);
        pop_control_bar_holder = (LinearLayout) contentView.findViewById(R.id.record_pop_control_bar_holder);
        ImageView back = (ImageView) contentView.findViewById(R.id.record_pop_control_bar_back_img);
        ImageView close2 = (ImageView) contentView.findViewById(R.id.record_pop_control_bar_close_img);
        close.setOnClickListener(this);
        back.setOnClickListener(this);
        close2.setOnClickListener(this);

        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new PaintDrawable());
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, statusBarHeight);

        contentView.findViewById(R.id.record_pop_parent).setOnClickListener(popupWindowClickFreeSpaceListener);
    }

    /**
     * 点击popupWindow其他空余位置的时候，将popupWindow关闭
     */
    public View.OnClickListener popupWindowClickFreeSpaceListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if ((int) pop_window2.getVisibility() == 0) {
                closeAnimation(pop_window2);
            } else {
                closeAnimation(pop_window1);
            }
        }
    };

    /**
     * 初始化pop界面
     */
    public void popInit() {
        Rect frame = new Rect();
        this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        statusBarHeight = frame.top;
        DisplayMetrics metrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        mWidth = metrics.widthPixels;
        mHeight = metrics.heightPixels;

//        popupWindow.setWidth(mWidth);
//        popupWindow.setHeight(mHeight);
    }

    /**
     * pop tabbar弹出动画
     *
     * @param layout
     */
    private void showAnimation(ViewGroup layout) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.center_music_window_close) {
                continue;
            }
            child.setOnClickListener(this);
            child.setVisibility(View.INVISIBLE);
            mHandler.postDelayed(new Runnable() {

                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                @Override
                public void run() {
                    child.setVisibility(View.VISIBLE);
                    ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 600, 0);
                    fadeAnim.setDuration(300);
                    PopAnimator kickAnimator = new PopAnimator();
                    kickAnimator.setDuration(150);
                    fadeAnim.setEvaluator(kickAnimator);
                    fadeAnim.start();
                }
            }, i * 50);
        }
    }

    /**
     * pop tabbar退出动画
     *
     * @param layout
     */
    private void closeAnimation(ViewGroup layout) {
        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.center_music_window_close) {
                continue;
            }
            child.setOnClickListener(this);
            mHandler.postDelayed(new Runnable() {

                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                @Override
                public void run() {
                    child.setVisibility(View.VISIBLE);
                    ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationY", 0, 600);
                    fadeAnim.setDuration(200);
                    PopAnimator kickAnimator = new PopAnimator();
                    kickAnimator.setDuration(100);
                    fadeAnim.setEvaluator(kickAnimator);
                    fadeAnim.start();
                    fadeAnim.addListener(new Animator.AnimatorListener() {

                        @Override
                        public void onAnimationStart(Animator animation) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            child.setVisibility(View.INVISIBLE);
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {
                            // TODO Auto-generated method stub

                        }
                    });
                }
            }, (layout.getChildCount() - i - 1) * 30);

            if (child.getId() == R.id.record_tabbar_temperature) {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        popupWindow.dismiss();
                    }
                }, (layout.getChildCount() - i) * 30 + 80);
            } else if (child.getId() == R.id.record_tabbar_early_pregnancy) {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        popupWindow.dismiss();
                    }
                }, (layout.getChildCount() - i) * 30 + 80);
            }
        }

    }

    /**
     * pop左右切换动画
     *
     * @param layout
     * @param fromX
     * @param fromY
     * @param turnFlag 1：表示向左移动
     */
    private void toLeftOrRightAnimation(ViewGroup layout, final float fromX, final float fromY, int turnFlag) {

        if (turnFlag == 1) {
            layout.setVisibility(View.VISIBLE);
        }

        for (int i = 0; i < layout.getChildCount(); i++) {
            final View child = layout.getChildAt(i);
            if (child.getId() == R.id.center_music_window_close) {
                continue;
            }
            child.setOnClickListener(this);

            if (turnFlag == 1) {
                child.setVisibility(View.INVISIBLE);
            }

            mHandler.postDelayed(new Runnable() {

                @TargetApi(Build.VERSION_CODES.HONEYCOMB)
                @Override
                public void run() {
                    child.setVisibility(View.VISIBLE);
                    ValueAnimator fadeAnim = ObjectAnimator.ofFloat(child, "translationX", fromX, fromY);
                    fadeAnim.setDuration(300);
                    PopAnimator kickAnimator = new PopAnimator();
                    kickAnimator.setDuration(150);
                    fadeAnim.setEvaluator(kickAnimator);
                    fadeAnim.start();
                }
            }, i * 50);
        }

        if (turnFlag == 1) {
            pop_control_bar_front_holder.setVisibility(View.GONE);
            pop_control_bar_holder.setVisibility(View.VISIBLE);
        } else {
            pop_control_bar_front_holder.setVisibility(View.VISIBLE);
            pop_control_bar_holder.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View v) {
        ViewPagerNumMsg viewPagerNumMsg = new ViewPagerNumMsg();
        switch (v.getId()) {
            case R.id.record_pop_control_bar_front_close_img://关闭
                closeAnimation(pop_window1);
                break;
            case R.id.record_tabbar_temperature://基础体温
                recordFragment.viewNum = 0;
                viewPagerNumMsg.setRespCode(0);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window1);
                break;
            case R.id.record_tabbar_mucus://宫颈粘液
                recordFragment.viewNum = 1;
                viewPagerNumMsg.setRespCode(1);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window1);
                break;
            case R.id.record_tabbar_menses://月经
                recordFragment.viewNum = 2;
                viewPagerNumMsg.setRespCode(2);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window1);
                break;
            case R.id.record_tabbar_conpulation://同房
                recordFragment.viewNum = 3;
                viewPagerNumMsg.setRespCode(3);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window1);
                break;
            case R.id.record_tabbar_ovulation://排卵试纸
                recordFragment.viewNum = 4;
                viewPagerNumMsg.setRespCode(4);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window1);
                break;
            case R.id.record_tabbar_more://更多
                toLeftOrRightAnimation(pop_window1, 0, -mWidth, 0);
                toLeftOrRightAnimation(pop_window2, mWidth, 0, 1);
                setDateToRecordFragment(chosedDateCalendar);
                break;
            case R.id.record_tabbar_early_pregnancy://早孕试纸
                recordFragment.viewNum = 5;
                viewPagerNumMsg.setRespCode(5);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window2);
                break;
            case R.id.record_tabbar_b_ultrasonic://B超
                recordFragment.viewNum = 6;
                viewPagerNumMsg.setRespCode(6);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window2);
                break;
            case R.id.record_tabbar_symptom://症状
                recordFragment.viewNum = 7;
                viewPagerNumMsg.setRespCode(7);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window2);
                break;
            case R.id.record_tabbar_note://备注
                recordFragment.viewNum = 8;
                viewPagerNumMsg.setRespCode(8);
                EventBus.getDefault().post(viewPagerNumMsg);
                setDateToRecordFragment(chosedDateCalendar);
                closeAnimation(pop_window2);
                break;
            case R.id.record_pop_control_bar_close_img://关闭
                closeAnimation(pop_window2);
                break;
            case R.id.record_pop_control_bar_back_img://向左切换
                toLeftOrRightAnimation(pop_window2, 0, mWidth, 1);
                toLeftOrRightAnimation(pop_window1, -mWidth, 0, 0);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        AppLog.i("LifeCycle MainActivity onResume!");

        syncRecordAndALData();

        isForeground = true;
        Bugtags.onResume(this);
        isActivityShown = true;
        AppLog.e("mainActivity:" + isChosedDateToRecord);
        Intent intent = getIntent();
        String fragmentName = intent.getStringExtra("fragmentName");
        if (fragmentName != null && fragmentName.equals("RecordFragment"))

            if (isBindedToHomeFragment) {
                isBindedToHomeFragment = false;
            }
        if (isChosedDateToRecord) {
            setDateToRecordFragment(chosedDateCalendar);
            isChosedDateToRecord = false;
        }

        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        isBLERegistered = true;

        THERMOMETER_CONNECTED_NUM = 0;
        BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
        //adapter不等于null，说明本机有蓝牙设备
        if (adapter != null) {
            AppLog.e("本机有蓝牙设备！");
            //如果蓝牙设备未开启
            if (adapter.isEnabled()) {
                if (mBLEThermometerService != null) {
                    operateThermometerScan(true);// 温度计扫描操作开始
                }
            }
        }


        PushUtil.resumePushService(this);

        if(isNeedChangeForecast){
            changeForecastStart();
        }
    }

    private void changeForecastStart() {
        isNeedChangeForecast = false;
        long zeroTime = DateUtil.getDateZeroTime2bit(new Date().getTime() / 1000) - 12 * 3600;
        int result = algorithm.executeAL(7, algorithm.getChangeForecastMensesStartDayInput(zeroTime), algorithm.getAllMensesConfirmStartHaveALCycleOutput(), 0);
        if(result == 234) g1Tog2Algorithm();
        dbManager.initDayUnitDSOutputsList2Memory(App.userName);
        AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
        algoUpdateMsg.setRespCode(1);
        EventBus.getDefault().post(algoUpdateMsg);
    }


    private void setDateToRecordFragment(String chosedDateCalendar) {

        if (null != getSupportFragmentManager().findFragmentByTag(getString(R.string.bottom_record))) {
            mRecordFragment = (RecordFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.bottom_record));
            mRecordFragment.setDateFromCalendar(chosedDateCalendar);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        PushUtil.pausePushService(this);
        Bugtags.onPause(this);
        isActivityShown = false;
        THERMOMETER_CONNECTED_NUM = 0;
        AppLog.e("onPause");
        isForeground = false;

        // 215 多账号登陆时跳转至LoginActivity时取消掉dialog，否则再次登陆进来仍然可以看到此dialog
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @SuppressLint("NewApi")
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            AppLog.e("LifeCycle ServiceConnection onServiceConnected");
            mBLEThermometerService = ((BLEThermometerService.LocalBinder) service).getService();
            // initialize初始化
            if (!mBLEThermometerService.initialize()) {// 如果温度计服务不初始化
                Toast.makeText(MainActivity.this, getString(R.string.bluetooth_unused), Toast.LENGTH_SHORT).show();
            } else {
                if(((BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter().isEnabled())
                    operateThermometerScan(true);// 温度计扫描操作打开
                else
                    mBLEThermometerService.openBluetooth(MainActivity.this);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBLEThermometerService = null;
        }
    };

    // 温度计扫描操作
    public void operateThermometerScan(final boolean enable) {
        AppLog.e("ThermometerService come in operateThermometerScan");
        if (mBLEThermometerService == null) {// 如果蓝牙温度计服务没有被绑定，就提示
            Toast.makeText(this, getString(R.string.bluetooth_init), Toast.LENGTH_SHORT).show();
            return;
        }

        if (enable) {
            AppLog.e("begin operateThermometerScan");
            if (mBLEThermometerService.thermometers.size() == 0) {
                mScanning = mBLEThermometerService.scanThermometers(mLeScanCallback);
            }
        } else {
            mScanning = false;
            mBLEThermometerService.stopScanThermometers(mLeScanCallback); // 停止扫描温度计
        }
    }

    @SuppressLint("NewApi")
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi,
                             byte[] scanRecord) {
            int i = 0;
            // deviceName = device.getName();
            final String address = device.getAddress();
            if (null != App.memory_preference_macAddress) {
                if (address.equals(App.memory_preference_macAddress)) {
                    AppLog.e("LeScanCallback ThermometerSensor0");
                    mBLEThermometerService.thermometers.add(device);

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if ((mBLEThermometerService.autoConnect)
                                    && (mBLEThermometerService.thermometers.size() > 0)) {
                                mBLEThermometerService.stopScanThermometers(mLeScanCallback);
                                //if(null != App.memory_preference_macAddress && device.getAddress().equals(App.memory_preference_macAddress) ){
                                mDevice = BluetoothAdapter.getDefaultAdapter()
                                        .getRemoteDevice(device.getAddress());
                                AppLog.e("LeScanCallback connectThermometer");
                                mBLEThermometerService.connectThermometer(mDevice
                                        .getAddress());
                            }
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mBLEThermometerService.stopScanThermometers(mLeScanCallback);
                            THERMOMETER_CONNECTED_NUM = 0;
                            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                            //adapter不等于null，说明本机有蓝牙设备
                            if (adapter != null) {
                                AppLog.e("本机有蓝牙设备！");
                                //如果蓝牙设备未开启
                                if (adapter.isEnabled()) {
                                    if (mBLEThermometerService != null) {
                                        operateThermometerScan(true);// 温度计扫描操作开始
                                    }
                                }
                            }
                        }
                    });
                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBLEThermometerService.stopScanThermometers(mLeScanCallback);
                        if (isActivityShown)
                            isBindedDevice(address);
                    }
                });

            }

        }
    };

    private boolean isBindedDevice(final String macAddress) {
        if (null == App.memory_preference_macAddress || "".equals(App.memory_preference_macAddress)) {
            Dialog alertDialog = new AlertDialog.Builder(MainActivity.this).
                    setTitle(getString(R.string.warm_prompt)).
                    setMessage(getString(R.string.hardware_is_unattach)).
                    setPositiveButton(getString(R.string.sure), new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(MainActivity.this, MyDeviceChooseActivity.class);
                            intent.putExtra("type", "bindThermometer");
                            startActivity(intent);
                        }
                    }).
                    setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    THERMOMETER_CONNECTED_NUM = 0;
                                    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                                    //adapter不等于null，说明本机有蓝牙设备
                                    if (adapter != null) {
                                        AppLog.e("本机有蓝牙设备！");
                                        //如果蓝牙设备未开启
                                        if (adapter.isEnabled()) {
                                            if (mBLEThermometerService != null) {
                                                operateThermometerScan(true);// 温度计扫描操作开始
                                            }
                                        }
                                    }
                                    dialog.dismiss();
                                }
                            }
                    ).
                    create();
            alertDialog.setCancelable(false);
            alertDialog.show();
            return false;
        } else if (macAddress == App.memory_preference_macAddress) {
            return true;
        } else return false;
    }

    public void filterTempWithValidTime() {

        //过滤掉错误测温时间的温度（2015/1/1之前的）
        if (null != temperatureInfoList && temperatureInfoList.size() != 0) {
            for (int i = temperatureInfoList.size() - 1; i >= 0; i--) {
                if (temperatureInfoList.get(i).getMeasureTime() < 1420041600) {
                    temperatureInfoList.remove(i);
                }
            }
            AppLog.e("  filterTempWithValidPastTime " + temperatureInfoList.size());
            if (temperatureInfoList.size() == 0) {
                if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                    setProgressDialogMsg(getString(R.string.bbt_past_post_fail));
                //Toast.makeText(MainActivity.this, R.string.bbt_past_post_fail, Toast.LENGTH_SHORT).show();
                return;
            }
        }

        //过滤未来的温度
        long time = new Date().getTime();
        AppLog.e("  filterTempWithValidFutureTime " + temperatureInfoList.size());
        if (null != temperatureInfoList && temperatureInfoList.size() != 0) {
            for (int i = temperatureInfoList.size() - 1; i >= 0; i--) {
                if (temperatureInfoList.get(i).getMeasureTime() > time) {
                    temperatureInfoList.remove(i);
                }
            }
            AppLog.e("  filterTempWithValidTime " + temperatureInfoList.size());
            if (temperatureInfoList.size() == 0) {
                if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                    setProgressDialogMsg(getString(R.string.bbt_future_post_fail));
                //Toast.makeText(MainActivity.this, R.string.bbt_future_post_fail, Toast.LENGTH_SHORT).show();
                return;
            }
        }

        //过滤掉温度值偏离的数据
        if (null != temperatureInfoList && temperatureInfoList.size() != 0) {
            for (int i = temperatureInfoList.size() - 1; i >= 0; i--) {
                if (temperatureInfoList.get(i).getTemperature() > 42.99 || temperatureInfoList.get(i).getTemperature() < 35) {
                    temperatureInfoList.remove(i);
                }
            }
            AppLog.e("  filterTempWithValidValue " + temperatureInfoList.size());
            if (temperatureInfoList.size() == 0) {
                if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                    setProgressDialogMsg(getString(R.string.bbt_valid_value_post_fail));
                //Toast.makeText(MainActivity.this, R.string.bbt_valid_value_post_fail, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void sendPregnantPeriod() {
        // if (App.status == 0) {
        long dateCurrentTwelfth = DateUtil.getStringToDate(DateUtil.getSimpleDate() + " 12:00:00");
        long dateStartPLQ = dateCurrentTwelfth;
        long dateFinishPLQ = dateCurrentTwelfth;
        if (null != App.DayUnitDSOutputMap.get(dateCurrentTwelfth)) {
            String period = App.DayUnitDSOutputMap.get(dateCurrentTwelfth).getPeriod(App.STATUS_BEIYUN);
            if (period.equals(DayUnitDSOutput.PERIOD_PLQ) || period.equals(DayUnitDSOutput.PERIOD_PLR)) {
                for (int i = 1; i < App.memory_preference_periodLen * 2; i++) {
                    if (null != App.DayUnitDSOutputMap.get(dateCurrentTwelfth + i * 24 * 3600)) {
                        if (!(App.DayUnitDSOutputMap.get(dateCurrentTwelfth + i * 24 * 3600).getPeriod(App.STATUS_BEIYUN).equals(DayUnitDSOutput.PERIOD_PLQ)) &&
                                !(App.DayUnitDSOutputMap.get(dateCurrentTwelfth + i * 24 * 3600).getPeriod(App.STATUS_BEIYUN).equals(DayUnitDSOutput.PERIOD_PLR))) {
                            dateFinishPLQ = dateCurrentTwelfth + (i - 1) * 24 * 3600;
                            break;
                        }
                    }
                }
                mBLEThermometerService.syncPregnantPeriod(dateStartPLQ, dateFinishPLQ);
            } else {
                for (int i = 1; i < App.memory_preference_periodLen * 2; i++) {
                    if (null != App.DayUnitDSOutputMap.get(dateCurrentTwelfth + i * 24 * 3600)) {
                        if (App.DayUnitDSOutputMap.get(dateCurrentTwelfth + i * 24 * 3600).getPeriod(App.STATUS_BEIYUN).equals(DayUnitDSOutput.PERIOD_PLQ) ||
                                App.DayUnitDSOutputMap.get(dateCurrentTwelfth + i * 24 * 3600).getPeriod(App.STATUS_BEIYUN).equals(DayUnitDSOutput.PERIOD_PLR)) {
                            dateStartPLQ = dateCurrentTwelfth + i * 24 * 3600;
                            break;
                        }
                    }
                }

                for (int i = 1; i < App.memory_preference_periodLen; i++) {
                    if (null != App.DayUnitDSOutputMap.get(dateStartPLQ + i * 24 * 3600)) {
                        if (!App.DayUnitDSOutputMap.get(dateStartPLQ + i * 24 * 3600).getPeriod(App.STATUS_BEIYUN).equals(DayUnitDSOutput.PERIOD_PLQ) &&
                                !App.DayUnitDSOutputMap.get(dateStartPLQ + i * 24 * 3600).getPeriod(App.STATUS_BEIYUN).equals(DayUnitDSOutput.PERIOD_PLR)) {
                            dateFinishPLQ = dateStartPLQ + (i - 1) * 24 * 3600;
                            break;
                        }
                    }
                }

                if (dateStartPLQ > dateCurrentTwelfth) {
                    mBLEThermometerService.syncPregnantPeriod(dateStartPLQ, dateFinishPLQ);
                }

            }
            AppLog.e("dateStartPLQ:" + dateStartPLQ + "dateFinishPLQ:" + dateFinishPLQ);
        }
        //  }
    }

    public void filterSameTemper() {

        if (null != temperatureInfoList && temperatureInfoList.size() > 1) {
            for (int i = temperatureInfoList.size() - 1; i > 0; i--) {
                for (int j = 0; j < i; j++) {
                    if (temperatureInfoList.get(j).getMeasureTime() == temperatureInfoList.get(i).getMeasureTime()) {
                        // AppLog.e("j:" + j + "time:" + temperatureInfoList.get(j).getMeasureTime()+ "i:" + i + "time:" +  temperatureInfoList.get(j).getMeasureTime());
                        temperatureInfoList.remove(i);
                        break;
                    }
                }
            }
        }
    }

    private void sendCurveMsg() {
//        List<CurveMsg> curveMsgs = new ArrayList<>();
//        if (null != syncTemperatureInfoList && syncTemperatureInfoList.size() != 0) {
//            for (int i = 0; i < syncTemperatureInfoList.size(); i++) {
//                if(syncTemperatureInfoList.get(i).getIsBBT() == 1){
//                    CurveMsg curveMsg = new CurveMsg();
//                    curveMsg.setDateStr(DateUtil.getDateStr(syncTemperatureInfoList.get(i).getMeasureTime()));
//                    curveMsg.setBBT(String.valueOf(syncTemperatureInfoList.get(i).getTemperature()));
//                    AppLog.i("curveMsg:" + curveMsg.getDateStr() + curveMsg.getBBT());
//                    curveMsgs.add(curveMsg);
//                }
//            }
//        }

        //EventBus.getDefault().post(new WebviewInitDataMsg());
        EventBus.getDefault().post(new CurveMsg());
    }

    @Subcriber
    public void initWebviewData(WebviewInitDataMsg webviewInitDataMsg) {
        //loadWebview();
    }

    @Subcriber
    private void setRecordDateToChangeRecordMsg(RecordInfo recordInfo) throws ParseException {
        String date = recordInfo.getDate();
        AppLog.e("setRecordDateToChangeRecordMsg:" + date);
        mViewPager.setCurrentItem(1);
    }

//    private void loadWebview() {
//        AppLog.i("loadWebview MainActivity initData.html");
//        webview.addJavascriptInterface(new CustomerData(this, App.userName), "CustomerData");
//        webview.loadUrl("file:///android_asset/health/initData.html");
//    }

    private IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();

        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_FOUND.getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_CONNECTED
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.THERMOMETER_DISCONNECTED
                .getName());
        intentFilter
                .addAction(BLEThermometerService.ThermometerMessage.RSSI_DATA_AVAILABLE.getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_OPEN
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_OPEN
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_FOUND
                .getName());
        intentFilter
                .addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_FOUND
                        .getName());

        intentFilter.addAction(BLEThermometerService.ThermometerMessage.TEMPERATURE_MEASUREMENT_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.INTERMEDIATE_TEMPERATURE_READ
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.HARDWARE_REVISION_READ
                .getName());
//        intentFilter.addAction(BLEThermometerService.ThermometerMessage.FIRMWARE_REVISION_READ
//                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.FIRMWARE_TIMESYNC_FOUND
                .getName());
        intentFilter.addAction(BLEThermometerService.ThermometerMessage.CLOSE_THERMOMETER_FOUND
                .getName());

        return intentFilter;
    }

    public void saveConnectTime() {

        long time = System.currentTimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
        Date date1 = new Date(time);
        String dateStr = format.format(date1);
        dbManager.updateUserPreference(App.userName, "lastConnectTime", dateStr);
        App.memory_preference_lastConnectTime = dateStr;
        MyDeviceMsg myDeviceMsg = new MyDeviceMsg();
        myDeviceMsg.setRespCode(App.LAST_CONNECT_TIME);
        EventBus.getDefault().post(myDeviceMsg);

    }

    public void saveTemperatureData2List(String temperature, String time) {
        long milliTimes = DateUtil.getStringToDate(time);
        UserTemperatureInfo userTemperatureInfo = new UserTemperatureInfo();
        userTemperatureInfo.setTemperatureId(UUID.randomUUID().toString());
        userTemperatureInfo.setTemperature(Double.valueOf(temperature));
        userTemperatureInfo.setUserName(App.userName);
        userTemperatureInfo.setMeasureTime(milliTimes);
        userTemperatureInfo.setEditTime(milliTimes);
        userTemperatureInfo.setIsBBT(0);
        userTemperatureInfo.setType(0);
        userTemperatureInfo.setSyncType(0);
        userTemperatureInfo.setIsDelete(0);
        temperatureInfoList.add(userTemperatureInfo);
    }

    public void filterTemperatureforSync() {
        if (null != temperatureInfoList && temperatureInfoList.size() != 0) {
            boolean todayTempOver4 = false; //今天的温度超过4天
            //boolean noValidTempUpload = true; //所有的温度都已经上传过
            //boolean over4Temp = true; //所有的天数都已经超过4条
            for (int i = 0; i < temperatureInfoList.size(); i++) {
                long measureTime = temperatureInfoList.get(i).getMeasureTime();
                int numTemper = dbManager.getTemperatureNum(App.userName, measureTime);
                if (numTemper < 4) {
                    //over4Temp = false;

                    if (numTemper == 0) temperatureInfoList.get(i).setIsBBT(1);
                    if (dbManager.checkTemperatureIsUploaded(App.userName, measureTime))
                        continue;

                    //noValidTempUpload = false;
                    syncTemperatureInfoList.add(temperatureInfoList.get(i));
                    dbManager.saveTempearatureData(temperatureInfoList.get(i));
                } else if (DateUtil.isToday(measureTime)) {
                    todayTempOver4 = true;
                }
            }

            if (null == syncTemperatureInfoList || syncTemperatureInfoList.size() == 0) {
//                if(!over4Temp && noValidTempUpload && !todayTempOver4)
//                    progressDialog.setMessage(getString(R.string.noValidTempUpload));
//                else if(over4Temp || todayTempOver4)
//                    progressDialog.setMessage(getString(R.string.over4Temp));
                if (!App.isBindActivityActive && !App.isMyDeviceActivityActive) {
                    if (todayTempOver4)
                        setProgressDialogMsg(getString(R.string.over4Temp));
                    else
                        setProgressDialogMsg(getString(R.string.noValidTempUpload));
                }
            }
            //Toast.makeText(MainActivity.this, R.string.Index_out_of_bounds, Toast.LENGTH_LONG).show();
        }
    }

    public void syncAndUploadRecordDatas() {
        if (InternetUtil.hasInternet()) {
            SyncRecordInfoMsg syncRecordInfoMsg = new SyncRecordInfoMsg();
            syncRecordInfoMsg.setSyncInActivity(SyncRecordInfoMsg.SYNC_RECORD_IN_MAINACTIVITY);
            SyncRecordInfo syncRecordInfo = new SyncRecordInfo(MainActivity.this, syncRecordInfoMsg);
            AppLog.e("SyncRecordInfoWithNetwork");
            syncRecordInfo.syncRecordInfoWithNetwork();
        } else {
            uploadTempers();
        }
    }

    @Subcriber
    private void syncRecordDataInMainActivity(SyncRecordInfoMsg syncRecordInfoMsg) {
        if (syncRecordInfoMsg.getSyncInActivity().equals(SyncRecordInfoMsg.SYNC_RECORD_IN_MAINACTIVITY)) {
            uploadTempers();
        }
    }

    private void uploadTempers() {
        JSONArray jsonArray = getUploadJsonArray();
        OKHttpUtil okHttpClient = new OKHttpUtil(MainActivity.this);
        String appendUrl = "sync/addSignsRecords.json";
        try {

            okHttpClient.add("authToken", App.authToken);
            okHttpClient.add("records", jsonArray);

            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    saveTemperature2DB(0);
                    saveRecord2DB(0);
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    temperUploadMsg.setRespCode(App.HTTP_RESP_FAIL);
                    EventBus.getDefault().post(temperUploadMsg);
                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {

                    try {
                        String str = response.body().string();
                        AppLog.i("addSignsRecords response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");
                        if (App.HTTP_RESP_OK == respCode) {
                            saveTemperature2DB(1);
                            saveRecord2DB(1);
                            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                            temperUploadMsg.setRespCode(App.HTTP_RESP_OK);
                            EventBus.getDefault().post(temperUploadMsg);
                            AppLog.i("addSignsRecords onResponse success!");
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadTempers();
                        } else if(respCode == 215){
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                                progressDialog = null;
                            }
                        }else {
                            saveTemperature2DB(0);
                            saveRecord2DB(0);
                            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                            temperUploadMsg.setRespCode(App.HTTP_RESP_FAIL);
                            EventBus.getDefault().post(temperUploadMsg);
                            AppLog.i("addSignsRecords onResponse failed! respCode = " + respCode);
                        }
                    } catch (JSONException e) {
                        saveTemperature2DB(0);
                        saveRecord2DB(0);
                        TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                        temperUploadMsg.setRespCode(App.HTTP_RESP_FAIL);
                        EventBus.getDefault().post(temperUploadMsg);
                        e.printStackTrace();
                    }
                }
            });
        } catch (JSONException e) {
            saveTemperature2DB(0);
            saveRecord2DB(0);
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setRespCode(App.HTTP_RESP_FAIL);
            EventBus.getDefault().post(temperUploadMsg);
            AppLog.i("UploadCycleData JSONException!");
            e.printStackTrace();
        }

    }

    private JSONArray getUploadJsonArray() {
        JSONArray jsonArray = new JSONArray();
        UserTemperatureInfo userTemperatureInfo = null;
        UserRecordData userRecordData = null;
        for (int i = 0; i < syncTemperatureInfoList.size(); i++) {
            userTemperatureInfo = syncTemperatureInfoList.get(i);
            UserTemperatureInfo[] userTemperatureInfos = new UserTemperatureInfo[1];
            userTemperatureInfos[0] = userTemperatureInfo;
            long time = userTemperatureInfo.getMeasureTime();
            userRecordData = dbManager.getSelectedDayRecordData(App.userName, DateUtil.getDateStr2bit(time));
            if (null != userRecordData.getId() && !"".equals(userRecordData.getId())) {
                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
                jsonArray.put(userRecordData.getUserRecordDataInfoJson());
            } else {
                userRecordData.setId(UUID.randomUUID().toString());
                userRecordData.setRecordDate(time);
                userRecordData.setUserName(App.userName);
                dbManager.saveRecordData(userRecordData);
                userRecordData.setUserTemperatureInfos(userTemperatureInfos);
                jsonArray.put(userRecordData.getUserRecordDataInfoJson());
            }
            syncRecordDataList.add(userRecordData);
        }
        return jsonArray;
    }

    private void saveTemperature2DB(int isSynced) {
        if (null != syncTemperatureInfoList && syncTemperatureInfoList.size() != 0) {
            for (int i = 0; i < syncTemperatureInfoList.size(); i++) {
                syncTemperatureInfoList.get(i).setSyncType(isSynced);
                dbManager.saveTempearatureData(syncTemperatureInfoList.get(i));
            }
            syncTemperatureInfoList.clear();
            temperatureInfoList.clear();
        }

        TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
        temperUploadMsg.setUpdateCode(1);
        EventBus.getDefault().post(temperUploadMsg);

        if (InternetUtil.hasInternet()) {
            SyncALDataMsg syncALDataMsg = new SyncALDataMsg();
            syncALDataMsg.setSyncInActivity(SyncALDataMsg.SYNC_IN_MAINACTIVITY);

            SyncALData syncALData = new SyncALData(MainActivity.this, syncALDataMsg);
            AppLog.e("SyncALDataWithNetwork");
            syncALData.SyncALDataWithNetwork();
        } else {
            updateCycleDatas(0);
        }
        // updateCycleDatas(isSynced);
    }

    private void saveRecord2DB(int isSynced) {
        if (null != syncRecordDataList && syncRecordDataList.size() != 0) {
            for (int i = 0; i < syncRecordDataList.size(); i++) {
                syncRecordDataList.get(i).setIsSynced(isSynced);
                dbManager.saveRecordData(syncRecordDataList.get(i));
            }
        }
        syncRecordDataList.clear();
        syncTemperatureInfoList.clear();
        temperatureInfoList.clear();
    }

    @Subcriber
    private void syncBBTChangeALData(SyncALDataMsg syncALDataMsg) {
        if (syncALDataMsg.getSyncInActivity().equals(SyncALDataMsg.SYNC_IN_MAINACTIVITY)) {
            if (algorithm != null) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        updateCycleDatas(1);
                    }
                }).start();
            }
        }
    }

    private void updateCycleDatas(int isSynced) {

        AppLog.i("algorithm bbt");
        if(null != dbManager.getCurrentDayCycle(App.userName)){
            int result = algorithm.executeAL(11, algorithm.getBBTDayInput(), algorithm.getBBTMucusCycleInput(), isSynced);
            if(result == 234)g1Tog2Algorithm();
        }
        else g1Tog2Algorithm();

        dbManager.initDayUnitDSOutputsList2Memory(App.userName);
        AppLog.e("MainActivity initDayUnitDSOutputsList2Memory!");

        sendCurveMsg();

        AlgoUpdateMsg algoUpdateMsg = new AlgoUpdateMsg();
        algoUpdateMsg.setRespCode(1);
        EventBus.getDefault().post(algoUpdateMsg);

        if (isSynced == 1) {
            JSONArray jsonArrayCycleDatas = algorithm.getCycleOutputJson();
            JSONArray jsonArrayUserDatas = algorithm.getDayOutputJson();
            JSONObject jsonObjectUserData = algorithm.getUserInfoJson();

            uploadCycleDatas(jsonArrayCycleDatas, jsonArrayUserDatas, jsonObjectUserData);
        }
    }

    private void uploadCycleDatas(final JSONArray jsonArrayCycleDatas, final JSONArray jsonArrayUserDatas, final JSONObject jsonObjectUserData) {

        OKHttpUtil okHttpClient = new OKHttpUtil(MainActivity.this);
        String appendUrl = "cycle/replaceCycle.json";
        try {
            AppLog.i("cycleData = " + jsonArrayCycleDatas);
            AppLog.i("userData = " + jsonArrayUserDatas);
            AppLog.i("userInfo = " + jsonObjectUserData);
            okHttpClient.add("authToken", App.authToken);
            AppLog.i("authToken = " + App.authToken);
            if (null != jsonArrayCycleDatas)
                okHttpClient.add("cycleData", jsonArrayCycleDatas);
            if (null != jsonArrayUserDatas)
                okHttpClient.add("userData", jsonArrayUserDatas);
            if (null != jsonObjectUserData)
                okHttpClient.add("userInfo", jsonObjectUserData);
            if (null == jsonArrayCycleDatas && null == jsonObjectUserData && null == jsonArrayUserDatas)
                return;
            okHttpClient.postAsync(appendUrl, okHttpClient.new BaseCallBack() {

                @Override
                public void onFailure(Request request, IOException e) {
                    algorithm.saveALData2Sqlite(0);
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    temperUploadMsg.setUpdateCode(9);
                    EventBus.getDefault().post(temperUploadMsg);

                    super.onFailure(request, e);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
                    try {
                        String str = response.body().string();
                        AppLog.i("cycle/replaceCycle response:" + str);
                        JSONObject respJSONObj = new JSONObject(str);
                        int respCode = respJSONObj.getInt("code");

                        if (200 == respCode) {
                            AppLog.i("UploadCycleData onResponse success!");
                            temperUploadMsg.setUpdateCode(9);
                            EventBus.getDefault().post(temperUploadMsg);
                        } else if (respCode == App.HTTP_RESP_TOKEN_TIME_OUT) {
                            OKHttpUtil.setNewToken();
                            uploadCycleDatas(jsonArrayCycleDatas, jsonArrayUserDatas, jsonObjectUserData);
                        } else {
                            algorithm.saveALData2Sqlite(0);
                            temperUploadMsg.setUpdateCode(9);
                            AppLog.i("UploadCycleData onResponse failed! respCode = " + respCode);
                            EventBus.getDefault().post(temperUploadMsg);
                        }
                    } catch (JSONException e) {
                        algorithm.saveALData2Sqlite(0);
                        e.printStackTrace();
                        temperUploadMsg.setUpdateCode(9);
                        EventBus.getDefault().post(temperUploadMsg);
                    }
                }
            });
        } catch (JSONException e) {
            AppLog.i("UploadCycleData JSONException!");
            algorithm.saveALData2Sqlite(0);
            e.printStackTrace();
            TemperUploadMsg temperUploadMsg = new TemperUploadMsg();
            temperUploadMsg.setUpdateCode(9);
            EventBus.getDefault().post(temperUploadMsg);

        }
    }

    @Subcriber
    private void dealTemperUploadMsg(TemperUploadMsg temperUploadMsg) {
        AppLog.i("Main temperUploadMsg:" + temperUploadMsg.toString());
        int eventBusCode = temperUploadMsg.getRespCode();
        switch (eventBusCode) {

            case App.HTTP_RESP_OK:
                if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                    setProgressDialogMsg(getString(R.string.bbt_post_success));
                dissmissProgressDiaLog();
                break;
            case App.HTTP_RESP_FAIL:
                if (!App.isBindActivityActive && !App.isMyDeviceActivityActive)
                    setProgressDialogMsg(getString(R.string.bbt_post_success));
                dissmissProgressDiaLog();
                break;
            case 3:
                isBindedToHomeFragment = true;
                break;
            case 9:

                break;
            default:
                break;
        }
    }

    public void setProgressDialogMsg(String message) {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.setMessage(message);
        }
    }

    public void dissmissProgressDiaLog() {
        (new Handler()).postDelayed(new Runnable() {
            @Override
            public synchronized void run() {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
            }
        }, 2500);
    }

    @Subcriber
    private void dealCalendarMsg(ChooseDate chooseDate) {
        mViewPager.setCurrentItem(1);
        RecordChange recordChange = new RecordChange();
        recordChange.setString(chooseDate.getChooseDate());
        EventBus.getDefault().post(recordChange);
//       RecordFragment.setDateFromCalendar(chooseDate);
//        setDateToRecordFragment("2016.07.09");
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        //注：回调 3
        Bugtags.onDispatchTouchEvent(this, event);
        return super.dispatchTouchEvent(event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppLog.i("LifeCycle MainActivity onDestroy");
        EventBus.getDefault().unregister(this);
        temperatureInfoList = null;
        syncTemperatureInfoList = null;
        syncRecordDataList = null;
        operateThermometerScan(false);// 温度计扫描操作停止
        if (mGattUpdateReceiver != null && isBLERegistered == true) {
            unregisterReceiver(mGattUpdateReceiver);// 不注册广播接收器
            isBLERegistered = false;
        }
        if (sign && mServiceConnection != null) {
            getApplicationContext().unbindService(mServiceConnection);//解绑服务
            AppLog.e("onDestroy unbindService");
            sign = false;
        }
        getApplicationContext().stopService(new Intent(MainActivity.this, BLEThermometerService.class));
        unregisterReceiver(mMessageReceiver);

        App.activityList.remove(this);
    }

    //    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        Log.d("bbbbb", adapter.getRightScroll() + "aaaa");
//        if (adapter.getRightScroll()) {
//            return super.dispatchTouchEvent(ev);
//        } else {
//            switch (ev.getAction()) {
//                case MotionEvent.ACTION_DOWN://按下如果‘仅’作为‘上次坐标’，不妥，因为可能存在左滑，motionValue大于0的情况（来回滑，只要停止坐标在按下坐标的右边，左滑仍然能滑过去）
//                    beforeX = ev.getX();
//                    break;
//                case MotionEvent.ACTION_MOVE:
//                    float motionValue = ev.getX() - beforeX;
//                    if (motionValue < 0) {//禁止左滑
//                        return true;
//                    }
//                    beforeX = ev.getX();//手指移动时，再把当前的坐标作为下一次的‘上次坐标’，解决上述问题
//
//                    break;
//                default:
//                    break;
//            }
//            return super.dispatchTouchEvent(ev);
//        }
//
//    }


    @Override
    public void onBackPressed() {
        if (mViewPager.getCurrentItem() == 2) {
            main_lin.setVisibility(View.VISIBLE);
            three.setVisibility(View.VISIBLE);

            mViewPager.setCurrentItem(0, false);

            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            DisplayUtil.setFullScreen(this, false);
        } else
            dualBackToExitApp();
    }

    private long exitTime = 0;

    private void dualBackToExitApp() {
        if (null != getSupportFragmentManager().findFragmentByTag(getString(R.string.bottom_record)) && getSupportFragmentManager().findFragmentByTag(getString(R.string.bottom_record)).isVisible()) {
            mRecordFragment = (RecordFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.bottom_record));
            mRecordFragment.checkChangeAndBackHome();
        } else {

            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(this, R.string.confirm_to_leave, Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
    }


    //    private void bindPushId() {
//        String pushId = JPushInterface.getRegistrationID(this);
//
//
//        PushManager.bindPushID(pushId);
//    }
    //for receive customer msg from jpush server
    private MessageReceiver mMessageReceiver;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                String messge = intent.getStringExtra(KEY_MESSAGE);
                String extras = intent.getStringExtra(KEY_EXTRAS);
                StringBuilder showMsg = new StringBuilder();
                showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                if (!ExampleUtil.isEmpty(extras)) {
                    showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                }
                setCostomMsg(showMsg.toString());
            }
        }
    }

    private void setCostomMsg(String msg) {
//        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//        if (null != msgText) {
//            msgText.setText(msg);
//            msgText.setVisibility(android.view.View.VISIBLE);
//        }
    }

    private void setAlias() {

        //调用JPush API设置Alias
        mAHandler.sendMessage(mAHandler.obtainMessage(Constant.MSG_SET_ALIAS, App.userName));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("aaa", logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("aaa", logs);
                    if (ExampleUtil.isConnected(getApplicationContext())) {
                        mAHandler.sendMessageDelayed(mAHandler.obtainMessage(Constant.MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        Log.i("aaa", "No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("aaa", logs);
            }

//            ExampleUtil.showToast(logs, getApplicationContext());
        }

    };


    private final Handler mAHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constant.MSG_SET_ALIAS:
                    Log.d("aaa", "Set alias in handler.");
                    JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    break;
            }
        }
    };


}
